<?php
/**
 * 处理图片上出的服务器端脚本
 */
$support_types = array('image/jpeg','image/png','image/pjpeg','image/gif');
$sizelimit = 5 * 1024;//5 M

$do = empty($_GET['do'])? 'upload':$_GET['do'];


/**
 * 1	OK
 * -1	unsupported types
 * -2	size too big
 * -3	upload error
 */
function checkPic($file){
	global $support_types,$sizelimit;
	if($file["error"] > 0){
		return -3;
	}
	if( !in_array($file['type'],$support_types)){
		return -1;
	}
	if($file["size"] / 1024 > $sizelimit){
		return -2;
	}
	return 1;
}


if($do == 'upload'){
	$msg = '';
	$file = $_FILES["attach"];
	switch(checkPic($file)){
		case -1:
			$msg = "unsupported types";
			echo json_encode(array(
				'status'=>0,
				'msg'=>$msg
			));
			break;
			case -2:
				$msg = "size too big";
				echo json_encode(array(
					'status'=>0,
					'msg'=>$msg
				));
			break;
			case -3:
				$msg = "upload error";
					echo json_encode(array(
					'status'=>0,
					'msg'=>$msg
				));
			break;
			case 1://success
				move_uploaded_file($file["tmp_name"],"tmp/" . $file["name"]);
				
				echo json_encode(array(
					'status'=>1,
					'data'=>array("name"=>$file["name"],
						"url"=>"php/tmp/".$file["name"])
				));
			break;
	}
}elseif($do == 'save'){
	
    $filepath = "tmp/" . $_GET['name'];

    $zoom = $_GET['zoom'];
    $x1 = $_GET["x1"];
    $y1 = $_GET["y1"];
    $x2 = $_GET["x2"];
    $y2 = $_GET["y2"];
	
	//原始尺寸
    list($widthtemp, $heighttemp) = getimagesize($filepath);
	
	//缩放后大小
    $width = $widthtemp * $zoom;
    $height = $heighttemp * $zoom;
	
    //新建一个真彩色图像
    $image_p = @imagecreatetruecolor($width, $height) or die("Cannot Initialize new GD image stream");
	
    $white = imagecolorallocate($image_p, 255, 255, 255);
    imagefilledrectangle($image_p, 0, 0, $width, $height, $white); // 填充背景色
    
    //从 JPEG 文件或 URL 新建一图像
    $image = imagecreatefromjpeg($filepath);
    //重采样拷贝部分图像并调整大小
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $widthtemp, $heighttemp);

    // Get new dimensions
    $new_width = $x2 - $x1;
    $new_height = $y2 - $y1;

    // Resample
    $image_p1 = imagecreatetruecolor($new_width, $new_height);
    $white = imagecolorallocate($image_p1, 255, 255, 255);
    imagefilledrectangle($image_p1, 0, 0, $new_width, $new_height, $white); // 填充背景色
    imagecopyresampled($image_p1, $image_p, 0, 0, $x1, $y1, $new_width, $new_height, $new_width, $new_height);
    
	$tmpavatar = "image/" .time(). $_GET['name'];
    // 将图片保存到服务器
    
    imagejpeg($image_p1, $tmpavatar, 100);
	
	$tmpavatar = "php/".$tmpavatar;
    echo json_encode(array("url"=>$tmpavatar));
}

?>
